package com.zhangyuji.controller;

import com.zhangyuji.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${upload.path}")
    private String SAVE_PATH;

    @PostMapping("/upload")
    public R<String> uploadFile(MultipartFile file){
        System.out.println(file);
        System.out.println(SAVE_PATH);
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));

        UUID uuid = UUID.randomUUID();
        System.out.println(uuid);
        String fileName = uuid + substring;
        File f = new File(SAVE_PATH);

        if (!f.exists()){
            f.mkdirs();
        }

        try {
            file.transferTo(new File(SAVE_PATH + fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }


    @GetMapping("/download")
    public void downLoad(String name, HttpServletResponse response){
        System.out.println(name);
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(SAVE_PATH + name));

            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;

            byte[] bytes = new byte[1024 * 10];

            while((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();

            }

            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
